package com.mars.common.fegin;


import com.ag.utils.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import com.mars.common.utils.PageParam;
import feign.RequestTemplate;
import feign.codec.EncodeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;

import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CustomSpringEncoder extends SpringEncoder {

	public CustomSpringEncoder(ObjectFactory<HttpMessageConverters> messageConverters) {
		super(messageConverters);
	}

	@Override
	public void encode(Object requestBody, Type bodyType, RequestTemplate request) throws EncodeException {
		if(requestBody instanceof PageParam) {
			PageParam pageParam = (PageParam) requestBody;
			JSONObject object = JsonUtils.formObject(pageParam);
			
            Map<String,Collection<String>> map = new HashMap<String,Collection<String>>(request.queries());
            for (String key : object.keySet()) {
                log.debug("putting {}", key);
                map.put(key, Arrays.asList(String.valueOf(object.get(key))));
            }
            request.queries(map);
        }
        else{
            super.encode(requestBody, bodyType, request);
        }
	}
}
